import { CodeBlock } from '@/modals/formModal/chatMessage/codeBlock'
import ReactMarkdown from 'react-markdown'
import rehypeMathjax from 'rehype-mathjax/svg'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import '../../result/index.less'

const regex = /\^(\[\d+\])+?\^/g
export default function MdResult({ content }) {
  if (!content) return ''

  let msg = ''
  try {
    msg = content.toString().replace(regex, match => {
      return ''
    })
  } catch (error) {
    console.error('Error during message replacement:', error)
    msg = content
  }
  return (
    <ReactMarkdown
      remarkPlugins={[remarkGfm, remarkMath]}
      rehypePlugins={[rehypeMathjax]}
      linkTarget="_blank"
      className="bs-mkdown inline-block max-w-full whitespace-break-spaces break-all text-sm text-text-answer"
      components={{
        code: ({ node, inline, className, children, ...props }) => {
          if (children.length) {
            if (children[0] === '▍') {
              return <span className="form-modal-markdown-span"> ▍ </span>
            }

            children[0] = (children[0] as string).replace('`▍`', '▍')
          }

          const match = /language-(\w+)/.exec(className || '')

          return !inline ? (
            <CodeBlock
              key={Math.random()}
              language={(match && match[1]) || ''}
              value={String(children).replace(/\n$/, '')}
              {...props}
            />
          ) : (
            <code className={className} {...props}>
              {' '}
              {children}{' '}
            </code>
          )
        }
      }}
    >
      {msg || ''}
    </ReactMarkdown>
  )
}
